<template>
	<div class="container">
		<el-form class="form" label-width="120px" label-position="top">
			<el-form-item label="请导入文件: ">
				<el-col :span="16">
					<div style="text-align: left">
						<input type="file" ref="file" />
					</div>
				</el-col>
			</el-form-item>
			<el-button :type="'primary'" @click="dialogTableVisible = true"
				>批量注册</el-button
			>
		</el-form>
		<el-form class="form" label-width="120px" label-position="top">
			<el-form-item label="学号">
				<el-col :span="16">
					<el-input
						type="text"
						placeholder="请输入学号"
						v-model.trim="formData.id"
					/>
				</el-col>
			</el-form-item>
			<el-form-item label="姓名">
				<el-col :span="16">
					<el-input
						type="text"
						placeholder="请输入姓名"
						v-model.trim="formData.name"
					/>
				</el-col>
			</el-form-item>
			<el-form-item label="密码: ">
				<el-col :span="16">
					<el-input
						type="password"
						placeholder="请输入密码"
						v-model.trim="formData.psd"
					/>
				</el-col>
			</el-form-item>
			<el-form-item label="确认密码: ">
				<el-col :span="16">
					<el-input
						type="password"
						placeholder="请确认密码"
						v-model.trim="formData.psd2"
					/>
				</el-col>
			</el-form-item>
			<el-form-item label="学院">
				<el-col :span="16">
					<el-input
						type="text"
						placeholder="请输入学院"
						v-model.trim="formData.xy"
					/>
				</el-col>
			</el-form-item>
			<el-form-item label="年级">
				<el-col :span="16">
					<el-input
						type="text"
						placeholder="请输入年级"
						v-model.trim="formData.grade"
					/>
				</el-col>
			</el-form-item>
			<el-button type="primary" @click="register">手动注册</el-button>
		</el-form>
		<router-link :to="login">已有账户? 请前往登录🎉🎉</router-link>
		<el-dialog v-model="dialogTableVisible">
			<h1>将要注册的用户</h1>
			<el-table :data="output" style="text-align: left" max-height="300">
				<el-table-column property="姓名" label="姓名" />
				<el-table-column property="学号" label="学号" />
				<el-table-column property="年级" label="年级" />
				<el-table-column property="院系" label="院系" />
			</el-table>
			<el-button @click="registerAll" type="primary">确定</el-button>
		</el-dialog>
	</div>
</template>

<script>
import { read, utils } from "xlsx";
import { ElMessage } from "element-plus";

export default {
	// eslint-disable-next-line vue/multi-word-component-names
	name: "Register",
	data() {
		return {
			login: {
				name: "login",
			},
			output: [],
			dialogTableVisible: false,
			formData: {
				id: "",
				name: "",
				psd: "",
				psd2: "",
				xy: "",
				grade: "",
			},
		};
	},
	methods: {
		readExcel(e) {
			const files = e.target.files;
			// 如果没有文件名
			if (files.length <= 0) {
				return false;
			} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
				alert("上传格式不正确，请上传xls或者xlsx格式");
				return false;
			}

			const fileReader = new FileReader();
			fileReader.onload = (ev) => {
				try {
					const data = ev.target.result;
					// 切换为新的调用方式
					const workbook = read(data, {
						type: "binary",
					});
					// 取第一张表
					const wsname = workbook.SheetNames[0];
					// 切换为新的调用方式 生成json表格内容
					// console.log(ws);
					this.output = utils.sheet_to_json(workbook.Sheets[wsname]);
					// 后续为自己对ws数据的处理
				} catch (e) {
					return false;
				}
			};
			fileReader.readAsBinaryString(files[0]);
		},
		register() {
			if (
				this.formData.id === "" ||
				this.formData.name === "" ||
				this.formData.psd === "" ||
				this.formData.grade === "" ||
				this.formData.department === ""
			) {
				ElMessage({
					message: "请将信息填写完整",
					type: "warning",
				});
				return;
			}
			if (this.formData.psd !== this.formData.psd2) {
				ElMessage({
					message: "两次输入密码不一致",
					type: "warning",
				});
				return;
			}
			let student = [
				{
					studentID: this.formData.id,
					studentName: this.formData.name,
					password: this.formData.psd,
					grade: this.formData.grade || "未知",
					department: this.formData.xy || "未知",
					score: 0,
					isFree: 0,
				},
			];
			fetch(`${this.$store.getters.point}/Admin/register`, {
				method: "POST",
				body: JSON.stringify(student),
				// mode: "no-cors",
				headers: {
					"Content-Type": "application/json",
				},
			})
				.then((response) => response.text())
				.then((result) => {
					let code = JSON.parse(result).code;
					if (parseInt(code)) {
						ElMessage({
							message: "注册成功",
							type: "success",
						});
					} else {
						ElMessage({
							message: "导入失败",
							type: "error",
						});
					}
				});
		},
		registerAll() {
			// console.log(this.output);
			let students = [];
			this.output.forEach((item) => {
				let student = {
					isFree: 0,
					grade: "未知",
					department: "未知",
					score: 0,
				};
				let keys = Object.keys(item);
				keys.forEach((key) => {
					if (/(姓名|名字)/.test(key)) {
						student["studentName"] = item[key];
					} else if (/密码/.test(key)) {
						student["password"] = item[key];
					} else if (/(学院|院系)/.test(key)) {
						student["department"] = item[key];
					} else if (/年级/.test(key)) {
						student["grade"] = item[key];
					} else if (/学号/.test(key)) {
						student["studentID"] = item[key];
					}
				});
				students.push(student);
			});
			// console.log(students);

			fetch(`${this.$store.getters.point}/Admin/register`, {
				method: "POST",
				body: JSON.stringify(students),
				// mode: "no-cors",
				headers: {
					"Content-Type": "application/json",
				},
			})
				.then((response) => response.text())
				.then((result) => {
					let code = JSON.parse(result).code;
					if (parseInt(code)) {
						ElMessage({
							message: "注册成功",
							type: "success",
						});
					} else {
						ElMessage({
							message: "导入失败",
							type: "error",
						});
					}
				});
		},
	},
	mounted() {
		this.$refs.file.addEventListener("change", (e) => {
			this.readExcel(e);
		});
	},
};
</script>

<style scoped>
.container {
	font-weight: bolder;
	width: 50%;
	margin: auto;
}

.form {
	margin-top: 30px;
}

a {
	text-decoration: none;
}
</style>
